﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleTranAccountData
{
	static public class getRemoteAsset
	{

		/// <summary>
		/// 取得日期區間的帳單
		/// </summary>
		/// <param name="start_date"></param>
		/// <param name="end_date"></param>
		public static void getAssetHtml(DateTime start_date, DateTime end_date)
		{
			CookieContainer cookie;
			DateTime query_date = start_date;

			#region ===================刪除目錄下所有檔案

			string fileFolder = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/accountDataFolder");
			string[] files = System.IO.Directory.GetFiles(fileFolder);
			foreach (string s in files)
			{
				System.IO.File.Delete(fileFolder + @"\" + System.IO.Path.GetFileName(s));
			}
			DO.Common.Trace.InfoWrite("getRemoteAsset", "刪除檔案");

			#endregion

			if (getLoginCookie(out cookie))
			{
				for ( double i = 0 ; i <= end_date.Subtract(start_date).Days ; i ++ ) {
					saveAssetHtml(cookie, start_date.AddDays(i));
				}
			}

			//登出

			logout(cookie);
		}


		/// <summary>
		/// 取得登入cookie
		/// </summary>
		private static bool getLoginCookie(out CookieContainer cookie)
		{
			cookie = new CookieContainer();

			string id = "C121114253";
			string pwd_md5 = "a5eba18779972a05f45585a270f89de1";

			#region =============登入mlid

			try
			{
				//登入mlid
				string _url = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/login_page");
				string param = "IDToken0=&IDToken1=" + id + "&IDToken2=" + pwd_md5 + "&IDButton=%E7%99%BB%E5%85%A5&goto=null&gx_charset=UTF-8";
				DO.Common.WebBrowser.getHTML(_url, param, "POST", cookie, "UTF-8");
				DO.Common.Trace.InfoWrite("getRemoteAsset", "登入 " + _url);
			}
			catch (Exception ex)
			{
				cookie = new CookieContainer();
				DO.Common.Trace.ErrorWrite("getRemoteAsset", ex.ToString());
				return false;
			}

			#endregion

			#region =============處理帳號

			try
			{
				//處理帳號
				string _url = "https://futures1.masterlink.com.tw/xt_check.asp";
				string param = "uid=" + id + "&pwd=" + pwd_md5;
				DO.Common.WebBrowser.getHTML(_url, param, "GET", cookie, "Big5");
				DO.Common.Trace.InfoWrite("getRemoteAsset", "處理帳號 " + _url);
			}
			catch (Exception ex)
			{
				cookie = new CookieContainer();
				DO.Common.Trace.ErrorWrite("getRemoteAsset", ex.ToString());
				return false;
			}

			#endregion

			#region =============檢查cookie
			
			CookieCollection cos;
			cos = cookie.GetCookies(new Uri("https://futures1.masterlink.com.tw/"));
			foreach (Cookie co in cos)
			{
				if (co.Name.Equals("iPlanetDirectoryPro"))
				{
					DO.Common.Trace.DebugWrite("getRemoteAsset", co.Name + "=" + co.Value);
					return true;
				}
			}

			#endregion

			DO.Common.Trace.InfoWrite("getRemoteAsset", "無法取得登入cookie!");
			return false;
		}

		private static bool saveAssetHtml(CookieContainer cookie, DateTime qdate)
		{


			try
			{

				string url_get = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/asset_page");
				string fileFolder = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/accountDataFolder");

				#region ===================取得html

				string paramdate = qdate.ToString("yyyyMMdd");
				string url_all = url_get + "?s_date1=" + paramdate;
				string assethtml = DO.Common.WebBrowser.getHTML(url_all, null, "GET", cookie, "big5");

				DO.Common.Trace.InfoWrite("getRemoteAsset", "asset url= " + url_all);

				using (System.IO.StreamWriter write = new System.IO.StreamWriter(fileFolder + @"\" + paramdate + ".html", false, System.Text.Encoding.GetEncoding("big5")))
				{
					write.Write(assethtml);
					write.Flush();
				}

				DO.Common.Trace.InfoWrite("getRemoteAsset", "filename= " + fileFolder + paramdate + ".html");

				#endregion

			}
			catch (Exception ex)
			{
				DO.Common.Trace.ErrorWrite("getRemoteAsset", ex.ToString());
				return false;
			}

			return true;
		}

		private static void logout(CookieContainer cookie)
		{
			try
			{
				//登出mlid
				string _url = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/logout_page");
				DO.Common.WebBrowser.getHTML(_url, null, "POST", cookie, "UTF-8");
				DO.Common.Trace.InfoWrite("getRemoteAsset", "登出 " + _url);
			}
			catch (Exception ex)
			{
				DO.Common.Trace.ErrorWrite("getRemoteAsset", ex.ToString());
			}
		}

	}
}
